﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using Antu.WebControls;
using Antu.Core.Components;
using Antu.Core.Services;
using System.Web.UI.WebControls;
using System.Web;
using Antu.WorkFlowFactory;
using System.Data;
using System.Web.UI.HtmlControls;
using EluZSProvider;

namespace WebSys.UI.OfficeFlow
{
    public class EdituserSkin : MPBasicTemplate
    {
        FlowFactoryProvider _FlowFactoryProvider = (FlowFactoryProvider)ProviderService.ProviderServiceMange.GetProvider("FlowFactoryProvider");
        EluZSDataProvider _EluZSDataProvider = (EluZSDataProvider)ProviderService.ProviderServiceMange.GetProvider("EluZSProvider");
        TextBox txtLoginName, txtUserName, txtOrderbyid, txtMobile, txtPASSWORD, txtNewPASSWORD;
        DropDownList ddlCompany0, ddlDepartment0, ddlCompany1, ddlCompany2, ddlCompany3, ddlCompany4,
            ddlDepartment1, ddlDepartment2, ddlDepartment3, ddlDepartment4;
        Button btnUpdate, btnAddDepSel, btnDel1, btnDel2, btnDel3, btnDel4, btnUpload;
        HtmlTableRow tr1, tr2, tr3, tr4;
        Label labRole;

        protected string UserId
        {
            get { if (base.Page.Session["UserId"] != null) { return base.Page.Session["UserId"].ToString(); } else { return string.Empty; } }
            set { base.Page.Session["UserId"] = value; }
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            InitControl();
            if (!Page.IsPostBack)
            {
                BindDepartmentInfo();
                BindUserRole(base.Page.Request["userid"]);
                HtmlImage img1 = (HtmlImage)FindControl("img1");
                string tturl = Antu.Core.Components.SiteSettings.DefaultSiteSettings.DefaultThemeFolderMapPath;
                string strurl = tturl.Substring(0, tturl.Length - 16) + "/ZhengShou/ZSManage/showfile.aspx?id=";
                img1.Src = strurl + _FlowFactoryProvider.GetQMId(base.Page.Request["userid"]);
            }

        }
        private void InitControl()
        {
            txtLoginName = (TextBox)FindControl("txtLoginName");
            txtUserName = (TextBox)FindControl("txtUserName");
            txtOrderbyid = (TextBox)FindControl("txtOrderbyid");
            txtMobile = (TextBox)FindControl("txtMobile");
            txtPASSWORD = (TextBox)FindControl("txtPASSWORD");
            txtNewPASSWORD = (TextBox)FindControl("txtNewPASSWORD");

            ddlCompany0 = (DropDownList)FindControl("ddlCompany0");
            ddlCompany1 = (DropDownList)FindControl("ddlCompany1");
            ddlCompany2 = (DropDownList)FindControl("ddlCompany2");
            ddlCompany3 = (DropDownList)FindControl("ddlCompany3");
            ddlCompany4 = (DropDownList)FindControl("ddlCompany4");
            ddlDepartment0 = (DropDownList)FindControl("ddlDepartment0");
            ddlDepartment1 = (DropDownList)FindControl("ddlDepartment1");
            ddlDepartment2 = (DropDownList)FindControl("ddlDepartment2");
            ddlDepartment3 = (DropDownList)FindControl("ddlDepartment3");
            ddlDepartment4 = (DropDownList)FindControl("ddlDepartment4");

            tr1 = (HtmlTableRow)FindControl("tr1");
            tr2 = (HtmlTableRow)FindControl("tr2");
            tr3 = (HtmlTableRow)FindControl("tr3");
            tr4 = (HtmlTableRow)FindControl("tr4");

            btnUpdate = (Button)FindControl("btnUpdate");
            btnAddDepSel = (Button)FindControl("btnAddDepSel");
            btnDel1 = (Button)FindControl("btnDel1");
            btnDel2 = (Button)FindControl("btnDel2");
            btnDel3 = (Button)FindControl("btnDel3");
            btnDel4 = (Button)FindControl("btnDel4");

            btnUpdate.Click += new EventHandler(btnUpdate_Click);
            btnAddDepSel.Click += new EventHandler(btnAddDepSel_Click);
            btnDel1.Click += new EventHandler(btnDel1_Click);
            btnDel2.Click += new EventHandler(btnDel2_Click);
            btnDel3.Click += new EventHandler(btnDel3_Click);
            btnDel4.Click += new EventHandler(btnDel4_Click);

            labRole = (Label)FindControl("labRole");
            btnUpload = (Button)FindControl("btnUpload");
            btnUpload.Click += new EventHandler(btnUpload_Click);
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            FileUpload picFile = (FileUpload)FindControl("QMImgFile");
            TextBox filename = (TextBox)FindControl("filename");
            DropDownList DropDownList1 = (DropDownList)FindControl("DropDownList1");
            if (picFile.HasFile)
            {
                HttpPostedFile postfile = picFile.PostedFile;
                string fileName = System.IO.Path.GetFileName(postfile.FileName);
                string fileext = fileName.Substring(fileName.LastIndexOf("."));
                if ((fileext.ToLower() == ".jpg") || (fileext.ToLower() == ".gif") || (fileext.ToLower() == ".bmp") || (fileext.ToLower() == ".jpeg"))
                {
                    try
                    {
                        if (!string.IsNullOrEmpty(postfile.FileName))
                        {
                            System.IO.Stream filestream = postfile.InputStream;
                            byte[] bFileContent = new byte[filestream.Length];
                            if (bFileContent.Length > 5242880)
                            {
                                HttpContext.Current.Response.Write("<script>alert('上传文件大于5M！');window.location.href=window.location.href;</script>");
                            }
                            else
                            {
                                if (bFileContent.Length > 0)
                                {
                                    filestream.Read(bFileContent, 0, bFileContent.Length);
                                    string guidstr = Guid.NewGuid().ToString().Replace("-", "").ToUpper();
                                    string filenametemp = fileName.Replace(fileext, "");
                                    _FlowFactoryProvider.UpdateQMContent(bFileContent, guidstr, base.Page.Request["userid"]);
                                    HttpContext.Current.Response.Write("<script>alert('文件上传成功！');window.location.href=window.location.href;</script>");
                                }
                            }
                        }
                        else
                        {
                            HttpContext.Current.Response.Write("<script>alert('文件名不得为空！');history.back();</script>");
                        }
                    }
                    catch
                    {
                        HttpContext.Current.Response.Write("<script>alert('上传出错！');history.back();</script>");
                    }
                }
                else
                {
                    HttpContext.Current.Response.Write("<script>alert('上传文件只支持jpg,gif,jpeg,bmp,doc,docx,xls格式');history.back();</script>");
                }
            }
            else
            {
                HttpContext.Current.Response.Write("<script>alert('请选择上传文件！');history.back();</script>");
            }
        }
        protected void BindData()
        {

        }

        #region 绑定单位及部门
        private void BindCompanyList()
        {
            string LoginUserId = base.Page.Request["userid"];
            DataTable dtSubDep = _FlowFactoryProvider.GetSubDepList(LoginUserId);
            if (dtSubDep.Rows.Count > 0)
            {
                for (int i = 0; i < dtSubDep.Rows.Count; i++)
                {
                    HtmlTableRow trTemp = this.FindControl("tr" + i.ToString()) as HtmlTableRow;
                    trTemp.Visible = true;
                    string strCompId = _FlowFactoryProvider.GetParentDepId(dtSubDep.Rows[i]["order_id"].ToString());
                    DropDownList ddlComp = this.FindControl("ddlCompany" + i.ToString()) as DropDownList;
                    BindCompList(ddlComp);
                    ddlComp.SelectedValue = strCompId;
                    DropDownList ddlDep = this.FindControl("ddlDepartment" + i.ToString()) as DropDownList;
                    CompanyChange(strCompId, ddlDep);
                    ddlDep.SelectedValue = dtSubDep.Rows[i]["order_id"].ToString();
                }
            }
            else
            {
                BindCompList(ddlCompany0);
                if (ddlCompany0.Items.Count > 0) { ddlCompany0.SelectedIndex = 0; }
                CompanyChange(ddlCompany0.SelectedValue, ddlDepartment0);
                if (ddlDepartment0.Items.Count > 0) { ddlDepartment0.SelectedIndex = 0; }
            }
        }
        #endregion

        #region 获取用户和部门信息
        public void BindDepartmentInfo()
        {
            //获取用户信息
            string userId = base.Page.Request["userid"];
            string dptId = string.Empty;
            if (!string.IsNullOrEmpty(userId))  //编辑
            {
                DataTable dt = _FlowFactoryProvider.GetUserById(userId);
                if (dt.Rows.Count > 0)
                {
                    txtLoginName.Text = dt.Rows[0]["LOGIN_NAME"].ToString();
                    txtUserName.Text = dt.Rows[0]["USER_NAME"].ToString();
                    txtOrderbyid.Text = dt.Rows[0]["ORDERBYID"].ToString();
                    txtMobile.Text = dt.Rows[0]["MOBILE"].ToString();
                    txtPASSWORD.Text = dt.Rows[0]["PASSWORD"].ToString();
                    txtNewPASSWORD.Text = dt.Rows[0]["PASSWORD"].ToString();
                    dptId = dt.Rows[0]["DEPARTID"].ToString();
                }
                BindCompanyList(); //绑定部门
            }
            else           //新增
            {
                BindCompList(ddlCompany0);
                if (ddlCompany0.Items.Count > 0) { ddlCompany0.SelectedIndex = 0; }
                CompanyChange(ddlCompany0.SelectedValue, ddlDepartment0);
                if (ddlDepartment0.Items.Count > 0) { ddlDepartment0.SelectedIndex = 0; }
            }
        }
        #endregion

        #region 修改用户信息/添加用户
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            string userId = base.Page.Request["userid"];
            string loginName = txtLoginName.Text;
            string userName = txtUserName.Text;
            string orderbyid = txtOrderbyid.Text;
            string mobile = txtMobile.Text;
            string password = txtPASSWORD.Text;
            string newpassword = txtNewPASSWORD.Text;

            if (txtPASSWORD.Text.CompareTo(txtNewPASSWORD.Text) == 0)
            {
                string strDepId = string.Empty;
                for (int i = 0; i < 5; i++)
                {
                    HtmlTableRow trTemp = (HtmlTableRow)FindControl("tr" + i.ToString());
                    DropDownList ddlDep = (DropDownList)FindControl("ddlDepartment" + i.ToString());
                    if (trTemp.Visible && !string.IsNullOrEmpty(ddlDep.SelectedValue))
                    {
                        strDepId = strDepId + ddlDep.SelectedValue + ",";
                    }
                }
                strDepId = strDepId.TrimEnd(',');
                string[] UserDepartId = strDepId.Split(',');
                if (!string.IsNullOrEmpty(userId))
                {
                    if (userDepartment(userId))
                    {
                        _FlowFactoryProvider.UpdateUserBasicInfo(userId, loginName, userName, orderbyid, mobile, password);
                    }
                    else
                    {
                        _FlowFactoryProvider.UpdateUserById(userId, loginName, userName, orderbyid, mobile, password, UserDepartId);
                    }
                    Antu.Utilities.UtilitiesPage.AlertDialog("修改成功", "");
                }
                else
                {
                    if (txtLoginName.Text.Trim() != "")
                    {
                        _FlowFactoryProvider.AddNewUser(Guid.NewGuid().ToString(), loginName, userName, orderbyid, mobile, password, UserDepartId);
                        Antu.Utilities.UtilitiesPage.AlertDialog("添加成功", "window.location.href('userlist.aspx');");
                    }
                    else
                    {
                        Antu.Utilities.UtilitiesPage.AlertDialog("用户登录名不能为空", "");
                    }
                }
            }
            else
            {
                Antu.Utilities.UtilitiesPage.AlertDialog("两次输入的密码不一致！", "");
            }
        }

        #endregion

        #region 判断st_user_department是否变化
        protected bool userDepartment(string userID)
        {
            string strDepId = string.Empty;
            for (int i = 0; i < 5; i++)
            {
                HtmlTableRow trTemp = this.FindControl("tr" + i.ToString()) as HtmlTableRow;
                DropDownList ddlDep = this.FindControl("ddlDepartment" + i.ToString()) as DropDownList;
                if (trTemp.Visible && !string.IsNullOrEmpty(ddlDep.SelectedValue))
                {
                    strDepId = strDepId + ddlDep.SelectedValue + ",";
                }
            }
            string strUserDepInfo = string.Empty;
            strUserDepInfo = _FlowFactoryProvider.UserDepartmentInfo(userID);
            if (strDepId != string.Empty && strDepId == strUserDepInfo)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion

        #region 添加选择列表
        protected void btnAddDepSel_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 5; i++)
            {
                HtmlTableRow trTemp = (HtmlTableRow)FindControl("tr" + i.ToString());
                if (!trTemp.Visible)
                {
                    trTemp.Visible = true;
                    DropDownList ddlComp = (DropDownList)FindControl("ddlCompany" + i.ToString());
                    BindCompList(ddlComp);
                    if (ddlComp.Items.Count > 0) { ddlComp.SelectedIndex = 0; }
                    DropDownList ddlDep = (DropDownList)FindControl("ddlDepartment" + i.ToString());
                    CompanyChange(ddlComp.SelectedValue, ddlDep);
                    if (ddlDep.Items.Count > 0) { ddlDep.SelectedIndex = 0; }
                    break;
                }
            }
        }
        #endregion

        #region 删除选择列表
        protected void btnDel1_Click(object sender, EventArgs e)
        {
            DelSelList(tr1);
        }
        protected void btnDel2_Click(object sender, EventArgs e)
        {
            DelSelList(tr2);
        }
        protected void btnDel3_Click(object sender, EventArgs e)
        {
            DelSelList(tr3);
        }
        protected void btnDel4_Click(object sender, EventArgs e)
        {
            DelSelList(tr4);
        }
        #endregion

        #region 单位的selectedindexchanged事件
        protected void ddlCompany0_SelectedIndexChanged(object sender, EventArgs e)
        {
            CompanyChange(ddlCompany0.SelectedValue, ddlDepartment0);
        }
        protected void ddlCompany1_SelectedIndexChanged(object sender, EventArgs e)
        {
            CompanyChange(ddlCompany1.SelectedValue, ddlDepartment1);
        }
        protected void ddlCompany2_SelectedIndexChanged(object sender, EventArgs e)
        {
            CompanyChange(ddlCompany2.SelectedValue, ddlDepartment2);
        }
        protected void ddlCompany3_SelectedIndexChanged(object sender, EventArgs e)
        {
            CompanyChange(ddlCompany3.SelectedValue, ddlDepartment3);
        }
        protected void ddlCompany4_SelectedIndexChanged(object sender, EventArgs e)
        {
            CompanyChange(ddlCompany4.SelectedValue, ddlDepartment4);
        }
        #endregion

        /// <summary>
        /// 根据选择的单位绑定部门
        /// </summary>
        /// <param name="SelComp">所选择的单位id</param>
        /// <param name="DepList">对应的部门dropdownlist</param>
        private void CompanyChange(string SelComp, DropDownList DepList)
        {
            DataTable dtbumen = _FlowFactoryProvider.GetDepartByType("parent", SelComp);
            DataTable dtDedepart = _FlowFactoryProvider.GetDepartByType("depart", SelComp);
            DepList.Items.Clear();
            if (dtbumen.Rows.Count > 0)
            {
                DataRow drbm = dtbumen.NewRow();
                dtbumen.Rows.InsertAt(drbm, 0);
                DepList.DataSource = dtbumen;
                DepList.DataTextField = "depart_name";
                DepList.DataValueField = "departid";
                DepList.DataBind();
            }
            else if (dtDedepart.Rows.Count > 0)
            {
                DataRow drdp = dtDedepart.NewRow();
                dtDedepart.Rows.InsertAt(drdp, 0);
                DepList.DataSource = dtDedepart;
                DepList.DataTextField = "depart_name";
                DepList.DataValueField = "departid";
                DepList.DataBind();
            }
            else
            {
                DataTable dt = dtbumen;
                DataRow dr = dt.NewRow();
                dt.Rows.Add(dr);
                DepList.DataSource = dt;
                DepList.DataTextField = "depart_name";
                DepList.DataValueField = "departid";
                DepList.DataBind();
            }
        }

        /// <summary>
        /// 绑定单位列表
        /// </summary>
        /// <param name="CompList"></param>
        private void BindCompList(DropDownList CompList)
        {
            DataTable dtdw = _FlowFactoryProvider.GetYJDepartmentList();
            if (dtdw.Rows.Count > 0)
            {
                DataRow dr = dtdw.NewRow();
                dtdw.Rows.InsertAt(dr, 0);
                CompList.DataSource = dtdw;
                CompList.DataTextField = "depart_name";
                CompList.DataValueField = "departid";
                CompList.DataBind();
            }
        }

        /// <summary>
        /// 点击删除时隐藏tr
        /// </summary>
        /// <param name="tr">要隐藏的tr</param>
        private void DelSelList(HtmlTableRow tr)
        {
            tr.Visible = false;
        }

        protected void BindUserRole(string userid)
        {
            ShowUserRoleLab(userid);
        }

        protected void ShowUserRoleLab(string userid)
        {
            DataTable dt = _FlowFactoryProvider.BindUserGroup(userid);
            if (dt.Rows.Count > 0)
            {
                string nRole = string.Empty;
                foreach (System.Data.DataRow drTemp in dt.Rows)
                {
                    nRole += drTemp["group_name"].ToString() + "<span style='color: #003300'><strong>|</strong></span>";
                }
                if (!string.IsNullOrEmpty(nRole))
                {
                    this.labRole.Text = "<span style='color: #003300'><strong>用户所属角色：</strong></span>" + nRole.Remove(nRole.Length - 54, 54);
                }
                else
                {
                    this.labRole.Text = "该用户还未配置任何角色";
                }
            }

        }


    }
}


